package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class RepresentativeDistrictService {

    def jurisdictionService
    def stateService

    static transactional = true

    /* CRUD */
    public RepresentativeDistrict create(RepresentativeDistrict rd) throws DAOException{
        rd.state.addToRepresentativeDistricts(rd)
        stateService.save(rd.state)
        save(rd)
        return rd
    }
    public void save(RepresentativeDistrict rd) throws DAOException{
        ServiceUtils.save(rd)
    }
    public void save(RepresentativeDistrict rd, boolean flush) throws DAOException{
        ServiceUtils.save(rd, flush)
    }
    public void delete(RepresentativeDistrict rd){
        if(rd == null){
            return
        }
        if(rd.state?.representativeDistricts?.contains(rd)){
            rd.state.representativeDistricts.remove(rd)
        }
        rd.delete(flush:true)
    }
    public RepresentativeDistrict merge(RepresentativeDistrict rd){
        return rd.merge()
    }
    public RepresentativeDistrict get(String rdId){
        return get(Long.parseLong(rdId))
    }
    public RepresentativeDistrict get(long rdId){
        return RepresentativeDistrict.get(rdId)
    }
    public Set<RepresentativeDistrict> getAll(){
        return RepresentativeDistrict.findAll()
    }
    /* END CRUD */

    public RepresentativeDistrict getByNameAndStateOrCreate(String name, State state, String longName){
        RepresentativeDistrict rd = getByNameAndState(name, state)
        if(rd == null){
            rd = new RepresentativeDistrict(
                name:name,
                longName:longName,
                state:state
            )
            rd = create(rd)
        }
        return rd
    }

    public RepresentativeDistrict getByNameAndState(String name, State state){
        RepresentativeDistrict rd = RepresentativeDistrict.findByNameAndState(name, state)
        return rd
    }
}

